<template>
  <div>
    <!-- 搜索框 -->
    <el-form :inline="true" :model="queryParams" style="margin-top: 20px; margin-left: 30px;">
      <el-row>
        <el-form-item label="订单编号">
          <el-input v-model="queryParams.medicineOrderNumber" placeholder="请输入编号" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="queryParams.userName" placeholder="请输入" style="width: 140px;"></el-input>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.medicineOrderStatus" placeholder="请选择状态" clearable style="width: 120px">
            <el-option v-for="item in orderOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="下单起始时间">
          <el-date-picker v-model="queryParams.medicineOrderCreateTime" type="date" placeholder="选择日期"
            value-format="yyyy-MM-dd" style="width: 150px">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="下单截止时间">
          <el-date-picker v-model="queryParams.medicineOrderOverTime" type="date" placeholder="选择日期"
            value-format="yyyy-MM-dd" style="width: 150px">
          </el-date-picker>
        </el-form-item>
      </el-row>
      <el-form-item inline>
        <el-button type="primary" @click="getList" icon="el-icon-search" size="mini">搜索</el-button>
        <el-button @click="resetHandler" icon="el-icon-refresh" size="mini">重置</el-button>
      </el-form-item>
    </el-form>
    <!--订单的表格显示  -->
    <el-table :data="tableData" v-loading="loading">
      <el-table-column width="55" align="center" />
      <el-table-column label="id" prop="medicineOrderId" width="70" align="center"></el-table-column>
      <el-table-column label="订单编号" prop="medicineOrderNumber" width="220" align="center"></el-table-column>
      <el-table-column label="地址" align="center" width="350">
        <template #default="{ row }">
          {{ row.medicineOrderEconomize }}{{ row.medicineOrderMarket }}{{ row.medicineOrderDistinguish }}{{
            row.medicineOrderAddress }}
        </template>
      </el-table-column>
      <el-table-column label="手机号码" prop="medicineOrderPhone" width="220" align="center"></el-table-column>
      <el-table-column label="所属用户" prop="userName" width="150" align="center"></el-table-column>
      <el-table-column label="订单状态" prop="medicineOrderStatus" width="150" align="center"
        :formatter="formatOrderStatus">
      </el-table-column>
      <el-table-column label="订单金额" prop="medicineOrderPrice" width="150" align="center"></el-table-column>
      <el-table-column label="下单时间" prop="medicineOrderCreateTime" width="220" align="center">
      </el-table-column>
      <el-table-column label="订单详情" width="100" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleViewDetail(scope.row.medicineOrderId)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum" :page-sizes="[5, 10, 15, 20]" :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>

    <!-- 订单详情弹窗 -->
    <el-dialog title="订单详情" :visible.sync="detailDialogVisible" width="60%" :before-close="handleCloseDialog">
      <div v-loading="detailLoading">
        <!-- 商品信息表格 -->
        <el-table :data="orderDetail || []" style="width: 100%" border v-if="orderDetail && orderDetail.length > 0">
          <el-table-column label="药品ID" prop="medicineId" width="80" align="center"></el-table-column>
          <el-table-column label="药品名称" prop="medicineName" min-width="150"></el-table-column>
          <el-table-column label="单价" prop="medicinePrice" width="100" align="center">
            <template #default="{ row }">{{ row.medicinePrice }}元</template>
          </el-table-column>
          <el-table-column label="购买数量" prop="purchaseNumber" width="100" align="center"></el-table-column>
          <el-table-column label="小计" width="120" align="center">
            <template #default="{ row }">{{ (row.medicinePrice * row.purchaseNumber).toFixed(2) }}元</template>
          </el-table-column>
        </el-table>

        <div v-if="!orderDetail || orderDetail.length === 0" style="text-align: center; padding: 20px;">
          暂无订单详情数据
        </div>
      </div>

      <!-- 对话框底部按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMedicineOrder, getMedicineOrderDetail } from '@/api/patient/order.js'
import { getDicts } from '@/api/system/dict/data.js'

export default {
  data() {
    return {
      // 加载状态
      loading: false,
      // 查询参数
      queryParams: {
        medicineOrderNumber: '',
        userName: '',
        medicineOrderStatus: '',
        medicineOrderCreateTime: '',
        medicineOrderOverTime: '',
        pageNum: 1,
        pageSize: 10
      },
      orderOptions: [],
      tableData: [],
      total: 0,

      // 订单详情相关
      detailDialogVisible: false,
      detailLoading: false,
      orderDetail: []
    }
  },
  created() {
    this.getList();
    // 查询订单状态字典
    this.getDicts("order_status").then((res) => {
      console.log("字典数据", res.data)
      this.orderOptions = res.data;
    });
  },
  methods: {
    // 获取字典数据
    getDicts(dictType) {
      return getDicts(dictType);
    },

    // 查看订单详情
    handleViewDetail(goodsOrderId) {
      console.log("订单id", goodsOrderId);
      this.detailDialogVisible = true;
      this.detailLoading = true;
      this.orderDetail = null;

      getMedicineOrderDetail(goodsOrderId).then(res => {
        console.log("订单详情", res);
        this.orderDetail = res.rows;


        this.detailLoading = false;
      }).catch(error => {
        console.error("获取订单详情失败:", error);
        this.$message.error("获取订单详情失败");
        this.detailLoading = false;
      });
    },

    // 关闭弹窗
    handleCloseDialog(done) {
      this.$confirm('确定关闭订单详情吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        done();
      }).catch(() => { });
    },

    // 格式化订单状态（使用动态字典）
    formatOrderStatus(row, column, cellValue) {
      if (!this.orderOptions || this.orderOptions.length === 0) {
        return cellValue;
      }

      const matchedItem = this.orderOptions.find(
        (item) => item.dictValue == cellValue
      );

      return matchedItem ? matchedItem.dictLabel : cellValue;
    },

    // 重置搜索条件
    resetHandler() {
      this.queryParams = {
        medicineOrderNumber: '',
        userName: '',
        medicineOrderStatus: '',
        medicineOrderCreateTime: '',
        medicineOrderOverTime: '',
        pageNum: 1,
        pageSize: 10
      }
      this.getList()
    },

    // 分页大小变化
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },

    // 当前页变化
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },

    // 获取订单列表
    getList() {
      this.loading = true;
      listMedicineOrder(this.queryParams).then(res => {
        console.log("订单数据", res)
        this.tableData = res.rows
        this.total = res.total
      }).finally(() => {
        this.loading = false;
      })
    }
  }
}
</script>

<style scoped>
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>